package com.itheima.reggie.common;


import com.itheima.reggie.entity.CommonColumn;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
//@Aspect
@Slf4j
public class CommonColumnAdvice {
    @Pointcut("execution(* com.itheima.reggie.controller.*Controller.save*(..)) "
            + "||"
            +"execution(* com.itheima.reggie.controller.*Controller.update*(..))")
    private void pt(){}

    @Around("pt()")
    public Object modifyColumn(ProceedingJoinPoint pjp) throws Throwable {
        log.info("aop执行了`");
        //调用连接点方法
        Object proceed = null;

            //获取用户id
            Long id = UserIdThreadLocal.getId();
            //获取形参
            Object[] args = pjp.getArgs();
            //强转成父类
            CommonColumn arg = (CommonColumn) args[0];
            //获取执行的方法名
            String name = pjp.getSignature().getName();
            //判断是否是添加
            if (name.startsWith("save")){
                arg.setCreateUser(id);
                arg.setCreateTime(LocalDateTime.now());
            }
            //设置修改时间
            arg.setUpdateUser(id);
            arg.setUpdateTime(LocalDateTime.now());
            proceed = pjp.proceed(args);

        //返回调用方法的返回值
        return proceed;
    }
}
